package com.zhihuichongcheng.application.ui.coordination.activity;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcel;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.FileUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.yirimao.video.JCVideoPlayerStandard;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.coordination.CoordinationFileBean;
import com.zhihuichongcheng.application.bean.coordination.DicBean;
import com.zhihuichongcheng.application.bean.cricle.CommentBean;
import com.zhihuichongcheng.application.bean.cricle.CricleImageInfo;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.cricle.activity.ShowImageActivity;
import com.zhihuichongcheng.application.util.OpenFiles;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/10/29.
 */

public class CoordinationDetailActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mImImage, mImDownload, mImDownloadType;
    private JCVideoPlayerStandard mVideo;
    private TextView mTvTitle, mTvType, mTvClassCategory, mTvContent, mTvStudyNum, mTvRemark, mTvFileSize;
    private List<CommentBean> mListData = new ArrayList<>();
    private String id;
    private ImageView mImMp3;
    private MediaPlayer mMediaPlayer;
    private ProgressBar mBar;
    private RelativeLayout mRlDownload;
    private CoordinationFileBean bean;
    private TextView mTvDownloadTitle, mTvDownloadSize, mTvDownloadProgress;
    private String path;
    private boolean isStart = true;
    private boolean isPrepar = false;
    private Runnable mRunnable;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private boolean flagFileDownloaded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coordination_detail);
        initView();
        initData();
    }

    private void initView() {
        mImDownloadType = (ImageView) findViewById(R.id.im_download_type);
        mTvDownloadTitle = (TextView) findViewById(R.id.tv_download_title);
        mTvDownloadSize = (TextView) findViewById(R.id.tv_download_size);
        mTvDownloadProgress = (TextView) findViewById(R.id.tv_download_progress);
        mRlDownload = (RelativeLayout) findViewById(R.id.rl_download);
        mBar = (ProgressBar) findViewById(R.id.progress_bar);
        mBar.setMax(100);
        mMediaPlayer = new MediaPlayer();
        mImMp3 = (ImageView) findViewById(R.id.im_mp3);
        mImMp3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isStart) {
                    mImMp3.setBackgroundResource(R.drawable.jc_pause_normal);
                    isStart = false;
                    if (isPrepar) {
                        mMediaPlayer.start();
                    }
                } else {
                    mImMp3.setBackgroundResource(R.drawable.ic_video_open);
                    isStart = true;
                    if (isPrepar) {
                        mMediaPlayer.pause();
                    }
                }
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                isPrepar = true;
                if (!isStart) {
                    mMediaPlayer.start();
                }
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mImMp3.setBackgroundResource(R.drawable.ic_video_open);
            }
        });
        mVideo = (JCVideoPlayerStandard) findViewById(R.id.video);
        mImDownload = (ImageView) findViewById(R.id.im_download);
        mImImage = (ImageView) findViewById(R.id.im_image);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvType = (TextView) findViewById(R.id.tv_type);
        mTvClassCategory = (TextView) findViewById(R.id.tv_class_category);
        mTvContent = (TextView) findViewById(R.id.tv_class_troduction_content);
        mTvStudyNum = (TextView) findViewById(R.id.tv_study_num);
        mTvRemark = (TextView) findViewById(R.id.tv_remark);
        mTvFileSize = (TextView) findViewById(R.id.tv_file_size);
        mImDownload.setOnClickListener(this);
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("id")) {
            id = intent.getStringExtra("id");
        }
        String title = null;
        if (intent != null && intent.hasExtra("title")) {
            title = intent.getStringExtra("title");
        }
        setTitle(title);
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        params.put("fileContentId", id);
        DialogUtil.showLoadDiadlog(mContext);
        mManager.post(NetworkAPI.Coordiantion_detail, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(mContext);
                bean = GsonUtil.praseFromStringToBean(value, CoordinationFileBean.class);
                if (bean.getContentType().equals("jpg") || bean.getContentType().equals("png")) {

                    Glide.with(mContext).load(bean.getContentUrl()).placeholder(R.drawable.ic_openclass_image_defalut).into(mImImage);
                    mImImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            List<CricleImageInfo> list = new ArrayList<>();
                            Parcel parcel = Parcel.obtain();
                            parcel.writeString(bean.getContentUrl());
                            CricleImageInfo cricleImageInfo = new CricleImageInfo(parcel);
                            cricleImageInfo.setJinbaoHomeImgUrl(bean.getContentUrl());
                            list.add(cricleImageInfo);
                            Intent intent = new Intent(mContext, ShowImageActivity.class);
                            intent.putParcelableArrayListExtra("list", (ArrayList) list);
                            intent.putExtra("index", 0);
                            mContext.startActivity(intent);
                            ((Activity) mContext).overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                        }
                    });
                } else if (bean.getContentType().equals("mp4")) {
                    mVideo.setUp(bean.getContentUrl(), "");
                    mVideo.setVisibility(View.VISIBLE);
                    mImImage.setVisibility(View.GONE);
                    mImDownload.setVisibility(View.GONE);
                    mVideo.thumbImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(mContext).load(R.drawable.ic_openclass_video_defalut).into(mVideo.thumbImageView);
                } else if (bean.getContentType().equals("mp3")) {
                    mImDownload.setVisibility(View.GONE);
                    mImMp3.setVisibility(View.VISIBLE);
                    mImImage.setVisibility(View.VISIBLE);
                    mImImage.setBackgroundResource(R.drawable.ic_openclass_music_defalut);
                    mMediaPlayer.setVolume(3.0f, 1.0f);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mMediaPlayer.reset();//把各项参数恢复到初始状态
                            try {
                                mMediaPlayer.setDataSource(bean.getContentUrl());
                                mMediaPlayer.prepare();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                } else if (bean.getContentType().equals("gif")) {
                    mVideo.setVisibility(View.GONE);
                    mImDownload.setVisibility(View.GONE);
                    mImImage.setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(bean.getContentUrl()).asGif().placeholder(R.drawable.ic_openclass_image_defalut).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(mImImage);
                } else {
                    String url = bean.getContentUrl();
                    String[] strs = url.split("/");
                    LogUtil.logD(strs[strs.length - 1]);
                    path = Constants.Const_Cache_Dir + "/" + strs[strs.length - 1];
                    File file = new File(path);
                    if (file.exists()) {
                        if (file.length() == bean.getFileSize()) {
                            flagFileDownloaded = true;
                            mImDownload.setImageResource(R.drawable.ic_play);
                            mImDownload.setVisibility(View.VISIBLE);
                        } else {
                            mImDownload.setVisibility(View.VISIBLE);
                        }
                    } else {
                        mImDownload.setVisibility(View.VISIBLE);
                    }
                    if (bean.getContentType().equals("pdf")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_pdf_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_pdf).into(mImDownloadType);
                    } else if (bean.getContentType().equals("doc")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_doc_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_doc).into(mImDownloadType);
                    } else if (bean.getContentType().equals("numbers")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_xcls_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_xlcs).into(mImDownloadType);
                    } else if (bean.getContentType().equals("xlsx")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_xcls_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_xlcs).into(mImDownloadType);
                    } else if (bean.getContentType().equals("rar") | bean.getContentType().equals("zip")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_other_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_zip).into(mImDownloadType);
                    } else if (bean.getContentType().equals("ppt")) {
                        Glide.with(mContext).load(R.drawable.ic_openclass_ppt_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_ppt).into(mImDownloadType);
                    } else {
                        Glide.with(mContext).load(R.drawable.ic_openclass_other_defalut).into(mImImage);
                        Glide.with(mContext).load(R.drawable.ic_coordination_other).into(mImDownloadType);
                    }
                }
                mTvContent.setText(bean.getSummary());
                mTvTitle.setText(bean.getFileName());
                DicBean dic = bean.getDirectory();
                if (dic != null) {
                    String dicStr = dic.getFileName();
                    if (TextUtils.isEmpty(dicStr)) {
                        dicStr = "";
                    }
                    mTvType.setText(dicStr);
                } else {
                    mTvType.setText("根目录");
                }
                mTvClassCategory.setText(bean.getContentType());
                mTvStudyNum.setText(bean.getDownloadCount());
                mTvFileSize.setText(FileUtil.getFormatSize(bean.getFileSize()));
                mTvRemark.setText(bean.getRemark());
            }

            @Override
            public void onFailure(String value) {
                DialogUtil.dismiss(mContext);
            }
        }, params);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
        mManager.doDelete(bean.getContentUrl());
    }

    @Override
    public void onClick(final View v) {
        switch (v.getId()) {
            case R.id.im_download:
                if (flagFileDownloaded) {
                    OpenFiles.openFile(this, path);
                    return;
                }
                String url = bean.getContentUrl();
                String[] strs = url.split("/");
                DownloadManager man = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                Uri uri = Uri.parse(bean.getContentUrl());
                DownloadManager.Request request = new DownloadManager.Request(uri);
                request.setNotificationVisibility(View.VISIBLE);
                request.setDestinationInExternalPublicDir("/ThreeWaterbeijing/download/", strs[strs.length - 1]);
                final long mDownloadId = man.enqueue(request);
                mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        mTvDownloadTitle.setText(bean.getFileName());
                        DownloadManager.Query q = new DownloadManager.Query();
                        q.setFilterById(mDownloadId);
                        Cursor cursor = ((DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE)).query(q);
                        cursor.moveToFirst();
                        int bytes_downloaded = cursor
                                .getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        cursor.close();
                        mTvDownloadSize.setText(FileUtil.getFormatSize(bytes_downloaded) + "/" + FileUtil.getFormatSize(bean.getFileSize()));
                        if (bytes_downloaded == bytes_total) {
                            flagFileDownloaded = true;
                            mImDownload.setImageResource(R.drawable.ic_play);
                            mImDownload.setVisibility(View.VISIBLE);
                            mRlDownload.setVisibility(View.GONE);
                        } else {
                            mBar.setProgress((int) ((bytes_downloaded) * 100 / bytes_total));
                            mRlDownload.setVisibility(View.VISIBLE);
                            mTvDownloadProgress.setText(mBar.getProgress() + "%");
                            mHandler.postDelayed(mRunnable, 100);
                        }


                    }
                };
                mHandler.postDelayed(mRunnable, 100);

                break;
            default:
                break;
        }
    }


}
